
#include "FramesMgr.h"

FramesMgr::FramesMgr(unsigned int frameRate, bool isLog)
	: m_expect(frameRate, isLog)
{
	
}

void FramesMgr::changeRunningState()
{
	m_global.m_bRunning = !m_global.m_bRunning;
}

void FramesMgr::changeFramesLogState()
{
	m_expect.setIsLog(!m_expect.getIsLog());
}

void FramesMgr::rectifyFrames()
{
	float curr = getWindowTime();
	float cost = curr - m_global.m_fLastFramePoint;
	float wait = m_expect.getFrameCost() - cost;
	if (wait > 0)
	{
		Sleep(wait * 1000.0f);
		curr = getWindowTime();
		cost = curr - m_global.m_fLastFramePoint;
	}
	m_global.m_fLastFramePoint = curr;
	m_global.m_fCurrFrameCost = cost;
}

void FramesMgr::update(float dt)
{
	rectifyFrames();
	auto cost = m_global.m_fCurrFrameCost;
	auto isRunning = m_global.m_bRunning;
	if (isRunning)
	{
		m_running.m_fTotalTime += cost;
	}

	if (m_expect.getIsLog())
	{
		m_log.m_uCurrSecondFrameCount++;
		m_log.m_fCurrSecondFrameCostTotal += m_global.m_fCurrFrameCost;
		if (m_log.m_fCurrSecondFrameCostTotal >= 1.0f)
		{
			m_log.m_uPrevSecondFrameRate = m_log.m_uCurrSecondFrameCount;
			m_log.m_uCurrSecondFrameCount = 0;
			m_log.m_fCurrSecondFrameCostTotal = 0.0f;	
		}
		std::cout << "FPS: " << m_log.m_uPrevSecondFrameRate << std::endl;
		if (isRunning)
		{
			std::cout << "game run time: " << m_running.m_fTotalTime << ", cost: " << m_global.m_fCurrFrameCost << std::endl;
		}
	}
}

